<?php

    class Application_Plugin_ShippingCalculator
    {

        // Defaults
        var $weight = 1;
        var $weight_unit = "lb";
        var $size_length = 4;
        var $size_width = 8;
        var $size_height = 2;
        var $size_unit = "in";
        var $debug = false; // Change to true to see XML sent and recieved 
        // Batch (get all rates in one go, saves lots of time)
        var $batch_ups = false; // Currently Unavailable
        var $batch_usps = true;
        var $batch_fedex = false; // Currently Unavailable
        // Config (you can either set these here or send them in a config array when creating an instance of the class)
        var $services;
        var $sender_zipcode = "97210";
        var $sender_state = "OR";
        var $sender_country = "US";
        var $to_zip = "55455";
        var $to_state = "MN";
        var $to_country = "US";
        //our access key 
        // var $ups_access = "6CC93EA7DCCA8622";
        //raeken ups access key
        var $ups_access = "6CC93EA7DCCA8622";
        //our ups user - var $ups_user = "raeken";
        var $ups_user = "Raeken";
        //our ups password var $ups_pass = "Hello200!";
        var $ups_pass = "Kteam666";
        var $ups_account;
        var $usps_userid;
        var $fedex_account = "510087062";
        var $fedex_meter = "118606179";
        var $key = "MObKh1bVH5xxGMKx";
        var $password = "Testradsoft123";
        //added array of services on 28 june

        public $services_usps = array('EXPRESS' => 'Express',
            'PRIORITY' => 'Priority',
            'PARCEL' => 'Parcel',
            'FIRST CLASS' => 'First Class',
            'EXPRESS SH' => 'Express SH',
                /* 'BPM' => 'BPM', */
                /*        'MEDIA ' => 'Media',
                  'LIBRARY' => 'Library' */
        );
        public $services_fedex = array(
            'INTERNATIONALPRIORITY' => 'Priority',
            'INTERNATIONALECONOMY' => 'Economy',
            'FEDEX2DAY' => '2 Day',
            'FEDEXEXPRESSSAVER' => 'Express Saver',
            'FEDEXGROUND' => 'Ground'
        );
        // Results
        var $rates;

        // Setup Class with Config Options
        function __construct($config = NULL)
        {

//            $adminconfig = Zend_Registry::get('SHIPPING_CONFIG');
//
//            if ($adminconfig)
//            {
//                foreach ($adminconfig as $k => $v)
//                    $this->$k = $v;
//            }
            if ($config)
            {
                foreach ($config as $k => $v)
                    $this->$k = $v;
            }

            //user address details
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
            {
                $this->user_id = $x->read()->rkn_uid;
                $user = $this->user = (array) $y;
                //$this->to_zip = "55455";
                $this->to_zip = $user['zip_code'];
//                var $to_state = "MN";
//                var $to_country = "US";
            }


            //prn($this);
        }

        //function to get service code array 
        function serviceCodes()
        {
            return array_flip(array_merge($this->services_usps, $this->services_fedex));
        }

        // Calculate
        function calculatePrices($userdata = array(), $weight = NULL)
        {
            
        }

        // Calculate FedEX 		$this->sender_zipcode .$this->to_state.'
        function calculate_fedex1($weight, $code = "FEDEXGROUND")
        {

            $this->weight = $weight;
            $url = FEDEX_URL;
            $data = '<?xml version="1.0" encoding="UTF-8" ?>
<FDXRateRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXRateRequest.xsd">
	<RequestHeader>
		<CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>
		<AccountNumber>' . $this->fedex_account . '</AccountNumber>
		<MeterNumber>' . $this->fedex_meter . '</MeterNumber>
		<CarrierCode>' . (in_array($code, array('FEDEXGROUND', 'GROUNDHOMEDELIVERY')) ? 'FDXG' : 'FDXE') . '</CarrierCode>
	</RequestHeader>
	<DropoffType>REGULARPICKUP</DropoffType>
	<Service>' . $code . '</Service>
	<Packaging>YOURPACKAGING</Packaging>
	<WeightUnits>LBS</WeightUnits>
	<Weight>' . number_format(($this->weight_unit != 'lb' ? convert_weight($this->weight, $this->weight_unit, 'lb') : $this->weight), 1, '.', '') . '</Weight>
	<OriginAddress>
		<StateOrProvinceCode>' . $this->sender_state . '</StateOrProvinceCode>
		<PostalCode>' . $this->sender_zipcode . '</PostalCode>

		<CountryCode>' . $this->sender_country . '</CountryCode>
	</OriginAddress>
	<DestinationAddress>
		<StateOrProvinceCode>' . $this->to_state . '</StateOrProvinceCode>
		<PostalCode>' . $this->to_zip . '</PostalCode>
		<CountryCode>' . $this->to_country . '</CountryCode>
	</DestinationAddress>
	<Payment>
		<PayorType>SENDER</PayorType>
	</Payment>
	<PackageCount>1</PackageCount>
</FDXRateRequest>';


            /* prn('<xmp>'.$data.'</xmp>');
              die; */

            // Curl
            $results = $this->curl($url, $data);

            //echo "<hr>"; prn(htmlentities($data));
            //echo "<hr>"; prn(htmlentities($results));
            // Debug
            if ($this->debug == true)
            {
                //echo "<pre>";
                print "<xmp>" . $data . "</xmp><br />";
                //	echo "<pre>";
                print "<xmp>" . $results . "</xmp><br />";
            }

            /* print "<xmp>".$data."</xmp><br />";
              prn("<xmp>".$results."</xmp>"); die; */
            // Match Rate
            //echo "vats";
            //echo "<pre>";
            //print_r($rate);
            preg_match('/<NetCharge>(.*?)<\/NetCharge>/', $results, $rate);

            if (empty($rate[1]))
            {
                preg_match('/<Message>(.*?)<\/Message>/', $results, $error);
                return $error[1];
            }


            return @(float) $rate[1];
        }

        function calculate_fedex($weight, $code = "FEDEXGROUND")
        {
            $this->weight = $weight;

            ini_set('max_execution_time', 0);
            //your account details here
            $key = $this->fedex_key;
            $password = $this->fedex_password;
            $account_number = $this->fedex_account;
            $meter_number = $this->fedex_meter;

            $xml = '<?xml version="1.0" encoding="UTF-8"?>
		<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v14"><SOAP-ENV:Body><ns1:RateRequest>
		<ns1:WebAuthenticationDetail>
		<ns1:UserCredential>
		<ns1:Key>' . $key . '</ns1:Key>
		<ns1:Password>' . $password . '</ns1:Password>
		</ns1:UserCredential></ns1:WebAuthenticationDetail>
		<ns1:ClientDetail>
		<ns1:AccountNumber>' . $account_number . '</ns1:AccountNumber>
		<ns1:MeterNumber>' . $meter_number . '</ns1:MeterNumber>
		</ns1:ClientDetail>
		<ns1:TransactionDetail><ns1:CustomerTransactionId> *** Rate Request v14 using PHP ***</ns1:CustomerTransactionId></ns1:TransactionDetail><ns1:Version><ns1:ServiceId>crs</ns1:ServiceId><ns1:Major>14</ns1:Major><ns1:Intermediate>0</ns1:Intermediate><ns1:Minor>0</ns1:Minor></ns1:Version><ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit><ns1:RequestedShipment>
		
		<ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType>
		<ns1:ServiceType>' . $code . '</ns1:ServiceType>
		<ns1:PackagingType>YOUR_PACKAGING</ns1:PackagingType>
		<ns1:TotalInsuredValue><ns1:Currency>USD</ns1:Currency></ns1:TotalInsuredValue>
		<ns1:Shipper><ns1:Contact><ns1:PersonName>Sender Name</ns1:PersonName><ns1:CompanyName>Sender Company Name</ns1:CompanyName><ns1:PhoneNumber></ns1:PhoneNumber></ns1:Contact><ns1:Address><ns1:StreetLines></ns1:StreetLines><ns1:City></ns1:City><ns1:StateOrProvinceCode></ns1:StateOrProvinceCode>
		<ns1:PostalCode>' . $this->sender_zipcode . '</ns1:PostalCode><ns1:CountryCode>' . $this->sender_country . '</ns1:CountryCode></ns1:Address></ns1:Shipper>
		<ns1:Recipient><ns1:Contact><ns1:PersonName>Recipient Name</ns1:PersonName><ns1:CompanyName>Company Name</ns1:CompanyName><ns1:PhoneNumber></ns1:PhoneNumber></ns1:Contact><ns1:Address><ns1:StreetLines></ns1:StreetLines><ns1:City></ns1:City><ns1:StateOrProvinceCode></ns1:StateOrProvinceCode>
		<ns1:PostalCode>' . $this->to_zip . '</ns1:PostalCode>
		<ns1:CountryCode>' . $this->to_country . '</ns1:CountryCode><ns1:Residential>false</ns1:Residential></ns1:Address></ns1:Recipient><ns1:ShippingChargesPayment><ns1:PaymentType>SENDER</ns1:PaymentType><ns1:Payor>
		<ns1:ResponsibleParty>
		<ns1:AccountNumber>' . $account_number . '</ns1:AccountNumber>
		</ns1:ResponsibleParty>
		</ns1:Payor></ns1:ShippingChargesPayment>
		<ns1:RateRequestTypes>ACCOUNT</ns1:RateRequestTypes><ns1:PackageCount>1</ns1:PackageCount><ns1:RequestedPackageLineItems><ns1:SequenceNumber>1</ns1:SequenceNumber>
		<ns1:GroupPackageCount>1</ns1:GroupPackageCount>
		<ns1:Weight><ns1:Units>LB</ns1:Units><ns1:Value>' . number_format(($this->weight_unit != 'lb' ? convert_weight($this->weight, $this->weight_unit, 'lb') : $this->weight), 1, '.', '') . '</ns1:Value></ns1:Weight>
		<ns1:Dimensions><ns1:Units>IN</ns1:Units></ns1:Dimensions>
		</ns1:RequestedPackageLineItems>
		</ns1:RequestedShipment></ns1:RateRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://wsbeta.fedex.com:443/web-services');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            $results = curl_exec($ch);

            // remove colons and dashes to simplify the xml
            /* $result_xml = str_replace(array(':','-'), '', $result_xml);
              $result = @simplexml_load_string($result_xml);

              print '<pre>';
              print 'Rate: $';
              print (string) $result->SOAPENVBody->RateReply->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
              print '<hr/>';
              print_r($result); */

            //$results = $this->curl($url,$data); //vats
            //echo "<hr>"; prn(htmlentities($data));
            //echo "<hr>"; prn(htmlentities($results));
            // Debug
            if ($this->debug == true)
            {
                //echo "<pre>";
                //print "<xmp>".$data."</xmp><br />";
                //	echo "<pre>";
                //echo "<pre>";
                print "<xmp>" . $results . "</xmp><br />";
            }

            /* print "<xmp>".$data."</xmp><br />";
              prn("<xmp>".$results."</xmp>"); die; */
            // Match Rate
            //echo "vats";
            //echo "<pre>";
            //print_r($rate);
            preg_match('/<TotalNetCharge><Currency>USD<\/Currency><Amount>(.*?)<\/Amount><\/TotalNetCharge>/', $results, $rate);
            //	prn($rate);
            if (empty($rate[1]))
            {
                //preg_match('/<Message>(.*?)<\/Message>/',$results,$error);
                if ($results != '')
                {
                    if (@$results->SOAPENVBody->RateReply->Notifications->Message != '')
                        return @$results->SOAPENVBody->RateReply->Notifications->Message;
                    else
                        return 'Please enter correct information.';
                }else
                {
                    return 'Please enter correct information.';
                }
            }


            return @(float) $rate[1];
        }

        // Calculate FedEX

        /* Array (
          [ups] => Array (
          [12] => 15.07
          [03] => 8.35
          [11] =>
          )
          [usps] => Array (
          [PRIORITY] => 8.10
          [PARCEL] => 7.62
          [FIRST CLASS] =>
          )
          [fedex] => Array (
          [FEDEX2DAY] => 18.55
          [FEDEXEXPRESSSAVER] => 13.53
          [FEDEXGROUND] => 6.34
          )
          ) */


        // Calculate USPS
        //testing zip code for usps 10022
        function calculate_usps($weight, $code = "Standard Post")
        {

            // added on 28  june


            $code = $this->services_usps;



            if ($weight)
            {
                $this->weight = $weight;
            }
            // Weight (in lbs)
            if ($this->weight_unit != 'lb')
                $weight = $this->convert_weight($weight, $this->weight_unit, 'lb');
            else
                $weight = $this->weight;
            // Split into Lbs and Ozs
            $lbs = floor($weight);
            $ozs = ($weight - $lbs) * 16;
            if ($lbs == 0 and $ozs < 1)
                $ozs = 1;
            // Code(s)
            $array = true;
            if (!is_array($code))
            {
                $array = false;
                $code = array($code);
            }

            $url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";


            if ($this->to_country == "US")
            {

                $data = 'API=RateV4&XML=<RateV4Request USERID="' . $this->usps_userid . '"><Revision/>';
                foreach ($code as $x => $c)
                {

                    $data.='<Package ID="1ST"><Service>' . $c . '</Service><FirstClassMailType>LETTER</FirstClassMailType><ZipOrigination>' . $this->sender_zipcode . '</ZipOrigination><ZipDestination>' . $this->to_zip . '</ZipDestination><Pounds>' . $lbs . '</Pounds><Ounces>' . $ozs . '</Ounces><Container/><Size>REGULAR</Size><Machinable>true</Machinable></Package>';
                }
                $data .= '</RateV4Request>';
            }
            else
            {
                $data = 'API=IntlRateV2&XML=<IntlRateV2Request USERID="' . $this->usps_userid . '">';

                $data.='<Package ID="1ST"><Revision>2</Revision><MailType>Package</MailType><GXG><POBoxFlag>N</POBoxFlag><GiftFlag>N</GiftFlag></GXG><ValueOfContents></ValueOfContents><Container>RECTANGULAR</Container><Size>REGULAR</Size><Width></Width><Length></Length><Height></Height><Girth></Girth><OriginZip>' . $this->sender_zipcode . '</OriginZip><Country>' . $this->to_country . '</Country><Pounds>' . $lbs . '</Pounds><Ounces>' . $ozs . '</Ounces><Container/><Machinable>true</Machinable></Package>';

                $data .= '</IntlRateV2Request>';


                //Production.ShippingAPIs.com/ShippingAPI.dll?API=IntlRateV2&XML=<IntlRateV2Request USERID="675TECHB4759"><Package ID="1ST"><Country>IN</Country><Pounds>5</Pounds><Ounces>5</Ounces></Package></IntlRateV2Request>
            }
            //echo "<hr>"; prn(htmlentities($data));echo "<hr>";
            // Curl


            $results = $chk = $this->curl($url, $data);


            //prn($results);
            //	$results = htmlentities($results);
            /* 		prn(htmlentities($results));echo "<hr>";
              die;
             */  // Debug
//		$results = "<xmp>".$results."</xmp>";
//		prn($results); die;

            $results = $xml = new SimpleXMLElement($results);

            if ($this->debug == true)
            {
                print "<xmp>" . $data . "</xmp><br />";
                print "<xmp>" . $results . "</xmp><br />";
            }



            $arrayobject = new ArrayObject($this->services_usps);
            $iterator = $arrayobject->getIterator();

            //prd($results);
            $myval = 0;

            foreach ($results->Package as $x => $package)
            {
                $myval = 1;

                $rates[$iterator->current()] = (float) $package->Postage->Rate <= 0 ? (string) $package->Error->Description : (float) $package->Postage->Rate;
                $iterator->next();
            }

            if ($myval == 0)
            {
                return array('Express' => 'Please enter a valid ZIP Code for the recipient.', 'Priority' => 'Please enter a valid ZIP Code for the recipient.', 'Parcel' => 'Please enter a valid ZIP Code for the recipient.', 'First Class' => 'Please enter a valid ZIP Code for the recipient.', 'Express SH' => 'Please enter a valid ZIP Code for the recipient.');
            }
            else
                return $rates;
            /* if($array == true) 
              return $rates;
              else return $rate[1]; */

            /* $rt=preg_match('/<Rate>(.+?)<\/Rate>/',$results,$rate);



              if(@$rate[1]){
              return(@$rate[1]);
              }else{
              return false;
              } */


            /* // Match Rate(s)
              preg_match_all('/<Package ID="([0-9]{1,3})">(.+?)<\/Package>/',$results,$packages);
              foreach($packages[1] as $x => $package) {
              preg_match('/<Rate>(.+?)<\/Rate>/',$packages[2][$x],$rate);
              $rates[$code[$package]] = $rate[1];
              }
              if($array == true) return $rates;
              else return $rate[1]; */
        }

        // Calculate UPS
        function calculate_ups($code = '01')
        {
            $url = "https://www.ups.com/ups.app/xml/Rate";
            $data = '<?xml version="1.0"?>  
<AccessRequest xml:lang="en-US">  
	<AccessLicenseNumber>' . $this->ups_access . '</AccessLicenseNumber>  
	<UserId>' . $this->ups_user . '</UserId>  
	<Password>' . $this->ups_pass . '</Password>  
</AccessRequest>  
<?xml version="1.0"?>  
<RatingServiceSelectionRequest xml:lang="en-US">  
	<Request>  
		<TransactionReference>  
			<CustomerContext>Bare Bones Rate Request</CustomerContext>  
			<XpciVersion>1.0001</XpciVersion>  
		</TransactionReference>  
		<RequestAction>Rate</RequestAction>  
		<RequestOption>Rate</RequestOption>  
	</Request>  
	<PickupType>  
		<Code>01</Code>  
	</PickupType>  
	<Shipment>  
		<Shipper>  
			<Address>  
				<PostalCode>' . $this->sender_zipcode . '</PostalCode>  
				<CountryCode>' . $this->sender_country . '</CountryCode>  
			</Address>  
		<ShipperNumber>' . $this->ups_account . '</ShipperNumber>  
		</Shipper>  
		<ShipTo>  
			<Address>  
				<PostalCode>' . $this->to_zip . '</PostalCode>  
				<CountryCode>' . $this->to_country . '</CountryCode>  
			<ResidentialAddressIndicator/>  
			</Address>  
		</ShipTo>  
		<ShipFrom>  
			<Address>  
				<PostalCode>' . (!empty($zip) ? $zip : $this->sender_zipcode ) . '</PostalCode>  
				<CountryCode>' . $this->sender_country . '</CountryCode>  
			</Address>  
		</ShipFrom>  
		<Service>  
			<Code>' . $code . '</Code>  
		</Service>  
		<Package>  
			<PackagingType>  
				<Code>02</Code>  
			</PackagingType>  
			<Dimensions>  
				<UnitOfMeasurement>  
					<Code>IN</Code>  
				</UnitOfMeasurement>  
				<Length>' . ($this->size_unit != "in" ? $this->convert_sze($this->size_length, $this->size_unit, "in") : $this->size_length) . '</Length>  
				<Width>' . ($this->size_unit != "in" ? $this->convert_sze($this->size_width, $this->size_unit, "in") : $this->size_width) . '</Width>  
				<Height>' . ($this->size_unit != "in" ? $this->convert_sze($this->size_height, $this->size_unit, "in") : $this->size_height) . '</Height>  
			</Dimensions>  
			<PackageWeight>  
				<UnitOfMeasurement>  
					<Code>LBS</Code>  
				</UnitOfMeasurement>  
				<Weight>' . ($this->weight_unit != "lb" ? $this->convert_weight($this->weight, $this->weight_unit, "lb") : $this->weight) . '</Weight>  
			</PackageWeight>  
		</Package>  
	</Shipment>  
</RatingServiceSelectionRequest>';

            // Curl
            $results = $this->curl($url, $data);

            // Debug
            if ($this->debug == true)
            {
                print "<xmp>" . $data . "</xmp><br />";
                print "<xmp>" . $results . "</xmp><br />";
            }

            // Match Rate
            preg_match('/<MonetaryValue>(.*?)<\/MonetaryValue>/', $results, $rate);
//            prd($results);
            return $rate[1];
        }

        // Calculate USPS
        function calculate_usps111($code = "Standard Post")
        {
            // Weight (in lbs)
            if ($this->weight_unit != 'lb')
                $weight = $this->convert_weight($weight, $this->weight_unit, 'lb');
            else
                $weight = $this->weight;
            // Split into Lbs and Ozs
            $lbs = floor($weight);
            $ozs = ($weight - $lbs) * 16;
            if ($lbs == 0 and $ozs < 1)
                $ozs = 1;
            // Code(s)
            $array = true;
            if (!is_array($code))
            {
                $array = false;
                $code = array($code);
            }

            $url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
            $data = 'API=RateV4&XML=<RateV4Request USERID="' . $this->usps_user . '">';
            foreach ($code as $x => $c)
                $data .= '<Package ID="' . $x . '"><Service>' . $c . '</Service><ZipOrigination>' . $this->sender_zipcode . '</ZipOrigination><ZipDestination>' . $this->to_zip . '</ZipDestination><Pounds>' . $lbs . '</Pounds><Ounces>' . $ozs . '</Ounces><Size>REGULAR</Size><Machinable>TRUE</Machinable></Package>';
            $data .= '</RateV4Request>';

            // Curl
            $results = $this->curl($url, $data);

            // Debug
            if ($this->debug == true)
            {
                print "<xmp>" . $data . "</xmp><br />";
                print "<xmp>" . $results . "</xmp><br />";
            }

            // Match Rate(s)
            preg_match_all('/<Package ID="([0-9]{1,3})">(.+?)<\/Package>/', $results, $packages);
            foreach ($packages[1] as $x => $package)
            {
                preg_match('/<Rate>(.+?)<\/Rate>/', $packages[2][$x], $rate);
                $rates[$code[$package]] = $rate[1];
            }
            if ($array == true)
                return $rates;
            else
                return $rate[1];
        }

        // Curl
        function curl($url, $data = NULL)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            if ($data)
            {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            $contents = curl_exec($ch);
            
            //prd($contents);
            return $contents;

            curl_close($ch);
        }

        // Convert Weight
        function convert_weight($weight, $old_unit, $new_unit)
        {
            $units['oz'] = 1;
            $units['lb'] = 0.0625;
            $units['gram'] = 28.3495231;
            $units['kg'] = 0.0283495231;

            // Convert to Ounces (if not already)
            if ($old_unit != "oz")
                $weight = $weight / $units[$old_unit];

            // Convert to New Unit
            $weight = $weight * $units[$new_unit];

            // Minimum Weight
            if ($weight < .1)
                $weight = .1;

            // Return New Weight
            return round($weight, 2);
        }

        // Convert Size
        function convert_size($size, $old_unit, $new_unit)
        {
            $units['in'] = 1;
            $units['cm'] = 2.54;
            $units['feet'] = 0.083333;

            // Convert to Inches (if not already)
            if ($old_unit != "in")
                $size = $size / $units[$old_unit];

            // Convert to New Unit
            $size = $size * $units[$new_unit];

            // Minimum Size
            if ($size < .1)
                $size = .1;

            // Return New Size
            return round($size, 2);
        }

        // Set Value
        function set_value($k, $v)
        {
            $this->$k = $v;
        }

        function calculate_ups_new($quantity = "1")
        {
            $quantity = $quantity;
            echo '<pre>';

            //Configuration
            $access = "6CC93EA7DCCA8622";
            $userid = "raeken";
            $passwd = "Hello200!";
            $wsdl = "assets/shipping/ups/wsdl/FreightRate.wsdl";
            $operation = "ProcessFreightRate";
            $endpointurl = '';
            $outputFileName = "XOLTResult.xml";

            function processFreightRate($quantity = "1")
            {
                //create soap request
                $option['RequestOption'] = 'RateChecking Option';
                $request['Request'] = $option;
                $shipfrom['Name'] = 'Good Incorporation';
                $addressFrom['AddressLine'] = '2010 WARSAW ROAD';
                $addressFrom['City'] = 'Roswell';
                $addressFrom['StateProvinceCode'] = 'GA';
                $addressFrom['PostalCode'] = '30076';
                $addressFrom['CountryCode'] = 'US';
                $shipfrom['Address'] = $addressFrom;
                $request['ShipFrom'] = $shipfrom;

                $shipto['Name'] = 'Sony Company Incorporation';
                $addressTo['AddressLine'] = '2311 YORK ROAD';
                $addressTo['City'] = 'TIMONIUM';
                $addressTo['StateProvinceCode'] = 'MD';
                $addressTo['PostalCode'] = '21093';
                $addressTo['CountryCode'] = 'US';
                $shipto['Address'] = $addressTo;
                $request['ShipTo'] = $shipto;

                $payer['Name'] = 'Payer inc';
                $addressPayer['AddressLine'] = '435 SOUTH STREET';
                $addressPayer['City'] = 'RIS TOWNSHIP';
                $addressPayer['StateProvinceCode'] = 'NJ';
                $addressPayer['PostalCode'] = '07960';
                $addressPayer['CountryCode'] = 'US';
                $payer['Address'] = $addressPayer;
                $shipmentbillingoption['Code'] = '10';
                $shipmentbillingoption['Description'] = 'PREPAID';
                $paymentinformation['Payer'] = $payer;
                $paymentinformation['ShipmentBillingOption'] = $shipmentbillingoption;
                $request['PaymentInformation'] = $paymentinformation;

                $service['Code'] = '308';
                $service['Description'] = 'UPS Freight LTL';
                $request['Service'] = $service;

                $handlingunitone['Quantity'] = $quantity;
                $handlingunitone['Type'] = array
                    (
                    'Code' => 'PLT',
                    'Description' => 'PALLET'
                );
                $request['HandlingUnitOne'] = $handlingunitone;

                $commodity['CommodityID'] = '';
                $commodity['Description'] = 'No Description';
                $commodity['Weight'] = array
                    (
                    'UnitOfMeasurement' => array
                        (
                        'Code' => 'LBS',
                        'Description' => 'Pounds'
                    ),
                    'Value' => '750'
                );
                $commodity['Dimensions'] = array
                    (
                    'UnitOfMeasurement' => array
                        (
                        'Code' => 'IN',
                        'Description' => 'Inches'
                    ),
                    'Length' => '23',
                    'Width' => '17',
                    'Height' => '45'
                );
                $commodity['NumberOfPieces'] = '45';
                $commodity['PackagingType'] = array
                    (
                    'Code' => 'BAG',
                    'Description' => 'BAG'
                );
                $commodity['DangerousGoodsIndicator'] = '';
                $commodity['CommodityValue'] = array
                    (
                    'CurrencyCode' => 'USD',
                    'MonetaryValue' => '5670'
                );
                $commodity['FreightClass'] = '60';
                $commodity['NMFCCommodityCode'] = '';
                $request['Commodity'] = $commodity;

                $shipmentserviceoptions['PickupOptions'] = array
                    (
                    'HolidayPickupIndicator' => '',
                    'InsidePickupIndicator' => '',
                    'ResidentialPickupIndicator' => '',
                    'WeekendPickupIndicator' => '',
                    'LiftGateRequiredIndicator' => ''
                );
                $shipmentserviceoptions['OverSeasLeg'] = array
                    (
                    'Dimensions' => array
                        (
                        'Volume' => '20',
                        'UnitOfMeasurement' => array
                            (
                            'Code' => 'CF',
                            'Description' => 'String'
                        )
                    ),
                    'Value' => array
                        (
                        'Cube' => array
                            (
                            'CurrencyCode' => 'USD',
                            'MonetaryValue' => '5670'
                        )
                    ),
                    'COD' => array
                        (
                        'CODValue' => array
                            (
                            'CurrencyCode' => 'USD',
                            'MonetaryValue' => '363'
                        ),
                        'CODPaymentMethod' => array
                            (
                            'Code' => 'M',
                            'Description' => 'For Company Check'
                        ),
                        'CODBillingOption' => array
                            (
                            'Code' => '01',
                            'Description' => 'Prepaid'
                        ),
                        'RemitTo' => array
                            (
                            'Name' => 'RemitToSomebody',
                            'Address' => array
                                (
                                'AddressLine' => '640 WINTERS AVE',
                                'City' => 'PARAMUS',
                                'StateProvinceCode' => 'NJ',
                                'PostalCode' => '07652',
                                'CountryCode' => 'US'
                            ),
                            'AttentionName' => 'C J Parker'
                        )
                    ),
                    'DangerousGoods' => array
                        (
                        'Name' => 'Very Safe',
                        'Phone' => array
                            (
                            'Number' => '453563321',
                            'Extension' => '1111'
                        ),
                        'TransportationMode' => array
                            (
                            'Code' => 'CARGO',
                            'Description' => 'Cargo Mode'
                        )
                    ),
                    'SortingAndSegregating' => array
                        (
                        'Quantity' => '23452'
                    ),
                    'CustomsValue' => array
                        (
                        'CurrencyCode' => 'USD',
                        'MonetaryValue' => '23457923'
                    ),
                    'HandlingCharge' => array
                        (
                        'Amount' => array
                            (
                            'CurrencyCode' => 'USD',
                            'MonetaryValue' => '450'
                        )
                    )
                );
                $request['ShipmentServiceOptions'] = $shipmentserviceoptions;

                echo "Request.......\n";
                print_r($request);
                echo "\n\n";
                return $request;
            }

            try
            {

                $mode = array
                    (
                    'soap_version' => 'SOAP_1_1', // use soap 1.1 client
                    'trace' => 1
                );

                // initialize soap client
                $client = new SoapClient($wsdl, $mode);

                //set endpoint url
                $client->__setLocation($endpointurl);


                //create soap header
                $usernameToken['Username'] = $userid;
                $usernameToken['Password'] = $passwd;
                $serviceAccessLicense['AccessLicenseNumber'] = $access;
                $upss['UsernameToken'] = $usernameToken;
                $upss['ServiceAccessToken'] = $serviceAccessLicense;

                $header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0', 'UPSSecurity', $upss);
                $client->__setSoapHeaders($header);


                //get response
                $resp = $client->__soapCall($operation, array(processFreightRate()));

                //get status
                echo "Response Status: " . $resp->Response->ResponseStatus->Description . "\n";

                //save soap request and response to file
                $fw = fopen($outputFileName, 'w');
                fwrite($fw, "Request: \n" . $client->__getLastRequest() . "\n");
                fwrite($fw, "Response: \n" . $client->__getLastResponse() . "\n");
                fclose($fw);
            }
            catch (Exception $ex)
            {
                print_r($ex);
            }
        }

    }

?>